package com.pig4cloud.pig.module.controller.wmj;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.module.api.entity.estate.Estate;
import com.pig4cloud.pig.module.api.entity.excel.WmjIdCardExcel;
import com.pig4cloud.pig.module.api.entity.property.Property;
import com.pig4cloud.pig.module.api.entity.wmj.WmjDoor;
import com.pig4cloud.pig.module.api.entity.wmj.WmjIdCard;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import com.pig4cloud.pig.module.service.property.IPropertyService;
import com.pig4cloud.pig.module.service.wmj.IWmjDoorService;
import com.pig4cloud.pig.module.service.wmj.IWmjIdCardService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 微门禁 门禁卡Controller
 *
 * @author ruoyi
 * @date 2022-12-08
 */
@Validated
@Api(value = "微门禁 门禁卡控制器", tags = {"微门禁 门禁卡管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/wmj/card")
public class WmjIdCardController {

    private final IWmjIdCardService wmjIdCardService;
	private final IPropertyService propertyService;
	private final IEstateService estateService;
	private final IWxUserService wxUserService;
	private final IWmjDoorService doorService;

    /**
     * 查询微门禁 门禁卡列表
     */
    @ApiOperation("查询微门禁 门禁卡列表")
    @PreAuthorize("@pms.hasPermission('module:wmjCard:list')")
    @GetMapping("/list")
    public TableDataInfo<WmjIdCard> list(@Validated WmjIdCard wmjIdCard) throws ParseException {
        QueryWrapper<WmjIdCard> qw = new QueryWrapper<>();
		if(wmjIdCard.getDoorId()!=null){
			qw.eq("door_id",wmjIdCard.getDoorId());
		}

		if(wmjIdCard.getIdCardNo()!=null){
			qw.eq("id_card_no",wmjIdCard.getIdCardNo());
		}
		qw.orderByDesc("create_time");

        TableDataInfo<WmjIdCard> td = PageUtils.buildDataInfo(wmjIdCardService.page(PageUtils.buildPage(),qw));
        List<WmjIdCard> list = td.getData();
        if(CollUtil.isNotEmpty(list)){
        	for (WmjIdCard idCard : list){

				Estate estate = estateService.findById(idCard.getEstateId());
				if(estate!=null){
					idCard.setEstateName(estate.getEstateName());
				}

				WmjDoor door = doorService.findById(idCard.getDoorId());
				if(door!=null){
					idCard.setDoorName(door.getDeviceName());
				}

				Property property = propertyService.findById(idCard.getPropertyId());
				if(property!=null){
					idCard.setPropertyName(property.getPropertyName());
				}
                if (idCard.getUserId()!=0){
                    WxUser wxUser = wxUserService.findById(idCard.getUserId());
                    if(wxUser!=null){
                        idCard.setNickName(wxUser.getNickName());
                    }
                }else {
                    idCard.setNickName("未绑定");
                }
                if(ObjectUtil.isEmpty(idCard.getExpireTime())){
                    SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
                    String time = "2099-12-31";
                    Date date =formatter.parse(time);
                    idCard.setExpireTime(date);
                }

			}
		}
        return td;
    }

    /**
     * 导出微门禁 门禁卡列表
     */
    @ApiOperation("导出微门禁 门禁卡列表")
    @PreAuthorize("@pms.hasPermission('module:wmjCard:export')")
    @SysLog("微门禁 门禁卡")
    @GetMapping("/export")
    public List export(@Validated WmjIdCard wmjIdCard) {
        List<WmjIdCard> list = wmjIdCardService.list();
        // ExcelUtil<WmjIdCard> util = new // ExcelUtil<>(WmjIdCard.class);
        return  list;// util.exportExcel(list, "微门禁 门禁卡");
    }

    /**
     * 获取微门禁 门禁卡详细信息
     */
    @ApiOperation("获取微门禁 门禁卡详细信息")
    @PreAuthorize("@pms.hasPermission('module:wmjCard:query')")
    @GetMapping("/{id}")
    public R<WmjIdCard> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        WmjIdCard wmjIdCard = wmjIdCardService.getById(id);
        return R.ok(wmjIdCard);
    }

    /**
     * 新增微门禁 门禁卡
     */
    @ApiOperation("新增微门禁 门禁卡")
    @PreAuthorize("@pms.hasPermission('module:wmjCard:add')")
    @SysLog("微门禁 门禁卡")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody WmjIdCard wmjIdCard) {
        return R.okByRow(wmjIdCardService.save(wmjIdCard) ? 1 : 0);
    }

    /**
     * 修改微门禁 门禁卡
     */
    @ApiOperation("修改微门禁 门禁卡")
    @PreAuthorize("@pms.hasPermission('module:wmjCard:edit')")
    @SysLog("微门禁 门禁卡")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody WmjIdCard wmjIdCard) {
        return R.okByRow(wmjIdCardService.updateById(wmjIdCard) ? 1 : 0);
    }

    /**
     * 删除微门禁 门禁卡
     */
    @ApiOperation("删除微门禁 门禁卡")
    @PreAuthorize("@pms.hasPermission('module:wmjCard:remove')")
    @SysLog("微门禁 门禁卡")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(wmjIdCardService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    @SysLog("门禁卡数据导入")
    @PreAuthorize("@ss.hasAnyPermi('module:wmjCard:import')")
    @PostMapping("/idCarNo")
    public R importDataIdCarNo(MultipartFile file, boolean updateSupport, Integer doorId) throws Exception {
//		ExcelUtil<WmjIdCardExcel> util = new ExcelUtil<>(WmjIdCardExcel.class);
//        List<WmjIdCardExcel> templateExcels = util.importExcel(file.getInputStream());
//
//        PigUser sysUser = SecurityUtils.getUser();
//        String operName = sysUser.getName();
//        String message = wmjIdCardService.importIdCardData(templateExcels, doorId,updateSupport,operName);
//        return R.ok(message);
		return R.ok();
    }


}
